package org.budo.excel.jdbc.driver.statement.impl;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.poi.ss.usermodel.Workbook;
import org.budo.excel.jdbc.driver.BudoExcelJdbcConnection;
import org.budo.excel.jdbc.driver.executor.PoiExcelStatementExecutor;
import org.budo.excel.jdbc.driver.statement.AbstractExcelStatement;
import org.budo.jdbc.driver.AbstractBudoJdbcPreparedStatement;
import org.budo.jdbc.driver.resultset.impl.MapArrayResultSet;
import org.budo.poi.util.WorkbookUtil;
import org.budo.support.lang.util.IoUtil;
import org.budo.support.lang.util.MapUtil;

/**
 * @author limingwei
 */
public class SHOW_TABLE_STATUS extends AbstractExcelStatement {
    private static final String NAME = "Name";

    private static final String ENGINE = "Engine";

    private static final String INNO_DB = "InnoDB";

    private static final String COMMENT = "Comment";

    @Override
    public void execute(PreparedStatement preparedStatement) throws SQLException {
        Connection connection = preparedStatement.getConnection();
        BudoExcelJdbcConnection excelJdbcConnection = (BudoExcelJdbcConnection) connection;
        PoiExcelStatementExecutor excelStatementExecutor = (PoiExcelStatementExecutor) excelJdbcConnection.statementExecutor();
        String url = excelStatementExecutor.getJdbcUrl().getUrl();
        String path = url.replace("jdbc:excel://", "");

        Workbook workbook = WorkbookUtil.newWorkbook(IoUtil.fileInputStream(path));
        int numberOfSheets = workbook.getNumberOfSheets();

        List<Map<?, ?>> maps = new ArrayList<Map<?, ?>>();
        for (int i = 0; i < numberOfSheets; i++) {
            String collectionName = (String) workbook.getSheetName(i);
            maps.add(MapUtil.stringMap(NAME, collectionName, ENGINE, INNO_DB, COMMENT, ""));
        }

        String[] columnNames = new String[] { NAME, ENGINE, COMMENT };
        ResultSet resultSet = new MapArrayResultSet(columnNames, maps.toArray(new Map[maps.size()]));
        ((AbstractBudoJdbcPreparedStatement) preparedStatement).setResultSet(resultSet);

        try {
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}